<template>
  <view class="main">
    <u-navbar title="请假申请" :autoBack="true">
    </u-navbar>
    <view class="btn-group">
      <!--     <view class="btn">
        <u-button :type="btnType1" :custom-style="customStyle" text="请假申请" @click="btnClick(1)"></u-button>
      </view>
      <view class="btn">
        <u-button :type="btnType2" :custom-style="customStyle" text="请假记录" @click="btnClick(2)"></u-button>
      </view> -->
      <view v-for="(item,index) in tabList" :key="index" @click="tabIndex = index;"
        style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
        <view style="font-size: 16px;margin-bottom: 15px;" :style="{'color':tabIndex==index?'#C4AD8C':'#000'}">
          {{item.name}}
        </view>
        <view v-show="tabIndex==index" style="width: 40px;height: 5px;background-color: #C4AD8C;border-radius: 3px;">
        </view>
      </view>

    </view>


    <view class="" style="margin: 10px;padding: 20px;background-color: #fff;border-radius: 12px;" v-if="tabIndex==0">
      <u--form :model="form" ref="uForm" labelWidth="70">
        <u-form-item label="请假类型" @click="typeColumnsShow = true" required>
          <u-input v-model="form.type" readonly>
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item label="开始时间" @click="beginTimePickerShow = true" required>
          <u-input v-model="form.beginTime" readonly />
        </u-form-item>
        <u-form-item label="结束时间" @click="endTimePickerShow = true" required>
          <u-input v-model="form.endTime" readonly />
        </u-form-item>
        <u-form-item label="请假时长">
          <u-input v-model="form.leaveDays" readonly>
            <template slot="suffix">
              /天
            </template>
          </u-input>
        </u-form-item>
        <u-form-item label="请假原因" required>

        </u-form-item>
        <u--textarea v-model="form.leaveExplain" placeholder="请输入内容" confirmType="done" ></u--textarea>
        <u-form-item label="审批人" @click="teacherPickerShow = true" required>
          <u-input v-model="form.copySendName" readonly>
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>

          </u-input>
        </u-form-item>
      </u--form>
      <u-button @click="submit" customStyle="background:#182044;color:#C4AD8C;border-radius:7px;margin-top:40px">提交
      </u-button>
    </view>

    <view v-if="tabIndex==1">
      <!-- 查询条件 -->
      <view class="flex-between" style="background-color: #fff;margin-top: -10px;padding:10px;">
        <view style="margin-right: 5px;" @click="typeColumnsShow = true">
          <u-input v-model="query.reasonName" readonly placeholder="选择请假类型" >
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>
          </u-input>
        </view>
        <view style="margin-right: 5px;" @click="statusColumnsShow = true">
          <u-input v-model="query.approvalStatusName" readonly placeholder="选择审核状态" >
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>
          </u-input>
        </view>

        <view>
          <u-button type="primary"
            customStyle="background:#182044;color:#C4AD8C;border-radius:7px;padding:17px;border:none;" size="small"
            text="重置" @click="reset"></u-button>
          <u-button type="primary"
            customStyle="background:#182044;color:#C4AD8C;border-radius:7px;padding:17px;border:none;margin-top:10rpx" size="small"
            text="查询" @click="getLeaveList"></u-button>
        </view>

      </view>
      <!-- 请假列表 -->
      <view style=";padding:10px;margin:10px;padding:10px;background-color: #fff;border-radius: 12px;" v-for="(e,i) in attendanceList" :key="i" @click="goDetail(e)">
        <view class="flex-between">
          <view class="applyInfo">
            <view>请假类型：{{findVal(e.reasonId)}}</view>
            <view>请假时长：{{e.leaveDays}}天</view>
            <view> 提交时间：{{e.createTime}}</view>
          </view>
          <view style="align-self: flex-start;margin-top: 10px;color: #C4AD8C;white-space:nowrap;" v-if="e.approvalStatus=='1'">退回</view>
          <view style="align-self: flex-start;margin-top: 10px;color: #C4AD8C;white-space:nowrap;" v-if="e.approvalStatus=='2'">待审核</view>
          <view style="align-self: flex-start;margin-top: 10px;color: #C4AD8C;white-space:nowrap;" v-if="e.approvalStatus=='3'">审核通过</view>
          <view style="align-self: flex-start;margin-top: 10px;color: #C4AD8C;white-space:nowrap;" v-if="e.approvalStatus=='4'">审核未通过</view>

        </view>
      </view>
      <view class="empty_warp" v-if="attendanceList.length==0">
            <image src="../../static/images/empty/list.png" class="empty" mode=""></image>
            <view class="empty_text">
              暂无数据
            </view>
      </view>
    </view>


    <u-picker :show="typeColumnsShow" :columns="typeColumns" title="请假类型" @cancel="typeColumnsShow = false;"
      @confirm="confirm">
    </u-picker>
    <u-picker :show="statusColumnsShow" :columns="statusColumns" title="审批状态" @cancel="statusColumnsShow = false;"
      @confirm="confirm2">
    </u-picker>
    <u-picker :show="beginTimePickerShow" :columns="dateColumns" title="开始时间" @cancel="beginTimePickerShow = false;"
      @confirm="beginTimeConfirm">
    </u-picker>
    <u-picker :show="endTimePickerShow" :columns="dateColumns" title="结束时间" @cancel="endTimePickerShow = false;"
      @confirm="endTimeConfirm">
    </u-picker>
     <u-picker :show="teacherPickerShow" :columns="teacherNameList" title="审批人" @cancel="teacherPickerShow = false;"
          @confirm="teacherConfirm">
        </u-picker>
    <!-- <u-datetime-picker :show="beginTimePickerShow" mode="datetime" @confirm="beginTimeConfirm"
      @cancel="beginTimePickerShow = false" :formatter="formatter" :minDate="new Date().getTime()"></u-datetime-picker> -->

    <!-- <u-datetime-picker :show="endTimePickerShow" mode="datetime" @confirm="endTimeConfirm"
      @cancel="endTimePickerShow = false" :formatter="formatter" :minDate="new Date().getTime()"></u-datetime-picker> -->
    <u-toast ref="uToast"></u-toast>
    <u-gap height="10" bgColor="#F8FAFB"></u-gap>
  </view>
</template>

<script>
   import {mapState,mapGetters} from "vuex"
  import {
    leaveApply,
    teacherLeaveApply,
    getLeaveReason,
    getTeacherLeaveReason,
    studentSubmitList,
    getUserInfo,
    attendanceList,
    getTeacherBossUser,
    getTeacherAttendanceList
  } from "@/api/user.js";
  export default {
    data() {
      return {
        query:{
          reasonName:'',
          approvalStatusName:''
        },
        teacherPickerShow:false,
        endTime: '',
        startTime: '',
        tabIndex: 0,
        tabList: [{
          name: '请假申请'
        }, {
          name: '请假记录'
        }],
        // tabIndex:1,
        endTimePickerShow: false,
        beginTimePickerShow: false,
        typeColumnsShow: false,
        leaveReason: [],
        typeColumns: [],
        teacherNameList:[],
        studentSubmitList: [],
        dateColumns: [
          [],
          ['上午', '下午']
        ],
        btnType1: 'primary',
        btnType2: '',
        form: {
          copySendId:'',
        },
        rules: {
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          }]
        },
        attendanceList:[],
        attendanceStatus:[]  ,//审批状态
        statusColumns:[],
        statusColumnsShow:false

      }
    },
    computed:{
      ...mapState(["userInfo","userType","userId",'dictDataList']),
    },
    watch:{
      tabIndex(val){
        console.log(val)
        if(val==1){
              this.getLeaveList()
        }
      }
    },
    onLoad(){
      this.getClockStatus();
      this.getType()
       this.getStudentSubmitList();
    },

    onShow() {
      // console.log(this.currentMonthDays())
      // console.log(this.getDaysBetween('2022-08-25 00:00:00','2022-08-26 18:00:00'))
      console.log("1111111111111",this.userType)
      this.dateColumns[0] = this.currentMonthDays();



    },


    methods: {
      findVal(id){
        // console.log(this.leaveReason.filter(e=>e.id==id))
        return this.leaveReason.filter(e=>e.id==id)[0] && this.leaveReason.filter(e=>e.id==id)[0].leaveReason;
      },
      teacherConfirm(e){
        this.form.copySendName= e.value[0];
        console.log(e)
        this.form.copySendId = this.studentSubmitList[e.indexs].id;
        this.teacherPickerShow = false;
      },
      getClockStatus(){
          let arr = this.dictDataList.filter(item=>item.dictType === 'attendance_approval_status');
          this.attendanceStatus = arr;
          this.statusColumns = [];
          this.statusColumns.push(arr.map(v => v.label));
      },
      async getStudentSubmitList() {
        // let userId = uni.getStorageSync('userId');

        // const  userInfo = await getUserInfo({id:userId})
        // console.log(userInfo)
        if(this.userType == 3){
          getTeacherBossUser({
            id:this.userId
          }).then(res=>{
              console.log("res",res);
              this.teacherNameList.push(res.data.map(v=>v.nickname))
              // console.log( this.teacherNameList)
              this.studentSubmitList = res.data;
          })
        }else if(this.userType == 4){
          studentSubmitList({studentId:this.userId}).then(res => {
            this.teacherNameList.push(res.data.map(v=>v.teacherName))
            // console.log( this.teacherNameList)
            this.studentSubmitList = res.data;
          })
        }

      },
      getType() {

        if(this.userType == 3){
          getTeacherLeaveReason().then(res=>{
            this.leaveReason = res.data;
            this.typeColumns = [];
            console.log(res.data.map(v => v.leaveReason))
            this.typeColumns.push(res.data.map(v => v.leaveReason))
          })

        }else if(this.userType == 4){
          getLeaveReason().then(res => {
            this.leaveReason = res.data;
            this.typeColumns = [];
            console.log(res.data.map(v => v.leaveReason))
            this.typeColumns.push(res.data.map(v => v.leaveReason))
          })
        }

      },
      reset(){
        this.query = {
          reasonName:'',
          approvalStatusName:''
        }
        this.getLeaveList()
      },
      getLeaveList(){

        if(this.userType == 3){
          getTeacherAttendanceList({ ...this.query,userType:2,userId:this.userId}).then((res)=>{
              console.log("attendanceList", res.data)
            this.attendanceList = res.data.reverse();
          })
        }else if(this.userType == 4){
          attendanceList({...this.query,userType:1,userId:this.userId}).then(res=>{
             console.log("attendanceList", res.data)
            this.attendanceList = res.data.reverse();
          })
        }
        console.log("attendanceList",this.attendanceList)
      },
      compareDate(dateTime1, dateTime2) {
        console.log(dateTime1,
          dateTime2)
        var formatDate1 = new Date(dateTime1);
        var formatDate2 = new Date(dateTime2);
        if (formatDate1 >= formatDate2) {
          return false;
        } else {
          return true;
        }
      },
      getDaysBetween(date1, date2) {
        var startDate = Date.parse(date1);
        var endDate = Date.parse(date2);
        if (startDate > endDate) {
          return 0;
        }
        if (startDate == endDate) {
          return 1;
        }
        var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
        return days;
      },
      goDetail(item){
        console.log("item",item)
        uni.navigateTo({
          url:'/pages/user/leaveDetail?detail='+JSON.stringify(item)
        })
      },

      /**
       * 获取当月的日期集合(yyyy-MM-dd)
       */
      currentMonthDays() {
        // 获取标准时间
        const date = new Date();
        // 获取当天日期
        const currentDay = date.getDate();
        // 获取当前月份（实际月份需要加1）
        const currentMonth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
        const nextMonth = date.getMonth() + 2 < 10 ? '0' + (date.getMonth() + 2) : date.getMonth() + 2;
        // 获取当前年份
        const currentYear = date.getFullYear();
        // 获取当前月有多少天
        const currentMonthDays = new Date(currentYear, currentMonth, 0).getDate();
        const nextMonthDays = new Date(currentYear, currentMonth + 1, 0).getDate();
        // 当前月份所有日期集合
        const currentMonthArr = [];
        const nextMonthArr = [];
        for (let day = 1; day <= currentMonthDays; day++) {
          // 截至当前日期为止
          if (day >= currentDay) {
            // 年月日(yyyy-MM-dd)
            let dateItem = currentYear + "-" + currentMonth + "-" + (day < 10 ? '0' + day : day)
            const week = new Date(dateItem).getDay();
            // console.log(week)
            if (week == 0) {
              dateItem += " 周日"
            } else if (week == 1) {
              dateItem += " 周一"
            } else if (week == 2) {
              dateItem += " 周二"
            } else if (week == 3) {
              dateItem += " 周三"
            } else if (week == 4) {
              dateItem += " 周四"
            } else if (week == 5) {
              dateItem += " 周五"
            } else if (week == 6) {
              dateItem += " 周六"
            }
            currentMonthArr.push(dateItem)
          }
        }
        for (let day = 1; day <= nextMonthDays; day++) {

          let dateItem = currentYear + "-" + nextMonth + "-" + (day < 10 ? '0' + day : day)
          const week = new Date(dateItem).getDay();
          // console.log(week)
          if (week == 0) {
            dateItem += " 周日"
          } else if (week == 1) {
            dateItem += " 周一"
          } else if (week == 2) {
            dateItem += " 周二"
          } else if (week == 3) {
            dateItem += " 周三"
          } else if (week == 4) {
            dateItem += " 周四"
          } else if (week == 5) {
            dateItem += " 周五"
          } else if (week == 6) {
            dateItem += " 周六"
          }



          currentMonthArr.push(dateItem)
        }
        return currentMonthArr;
      },

      formatter(type, value) {
        // console.log(type)
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        if (type === 'hour') {
          return `${value}时`
        }
        if (type === 'minute') {
          return `${value}分`
        }
        return value
      },
      endTimeConfirm(e) {
        this.endTimePickerShow = false;

        if (e.value[1] == '上午') {
          this.endTime = '12:00:00';
        }
        if (e.value[1] == '下午') {
          this.endTime = '23:59:59';
        }
        this.form.endTime = e.value[0] + " " + e.value[1]
        let date = e.value[0].substring(0, 10) + " " + this.endTime
        this.form.leaveEndTime = new Date(date).getTime();
        // this.form.leaveEndTime = e.value[0].substring(0, 10) + "T" + this.endTime;
        if (!this.compareDate(this.form.beginTime.substring(0, 10) + " " + this.startTime, e.value[0].substring(0, 10) +
            " " + this.endTime)) {

          return this.$refs.uToast.show({
            type: 'error',
            message: '结束时间必须大于开始时间'
          });
          W
        }
        this.form.leaveDays = parseFloat((this.getDaysBetween((this.form.beginTime.substring(0, 10) + " " + this
          .startTime), (this.form.endTime.substring(0, 10) + " " + this.endTime)))).toFixed(1)

        // let date = new Date(e.value);
        // let year = date.getFullYear();
        // let month = date.getMonth() + 1;
        // if (month < 10) {
        //   month = '0' + month;
        // }
        // let day = date.getDay() + 1;
        // if (date < 10) {
        //   date = '0' + date;
        // }
        // let hour = date.getHours();
        // if (hour < 10) {
        //   hour = '0' + hour;
        // }
        // let mins = date.getMinutes();
        // if (mins < 10) {
        //   mins = '0' + mins
        // }
        // this.form.endTime = year + '-' + month + '-' + day + " " + hour + ":" + mins + ":" + "00";

        // console.log(e)
        // console.log(this.form.beginTime)
      },

      beginTimeConfirm(e) {
        console.log(e)
        this.beginTimePickerShow = false;

        if (e.value[1] == '上午') {
          this.startTime = '00:00:00';
        }
        if (e.value[1] == '下午') {
          this.startTime = '12:00:00';
        }
        // let date = new Date(e.value);
        // let year = date.getFullYear();
        // let month = date.getMonth() + 1;
        // if (month < 10) {
        //   month = '0' + month;
        // }
        // let day = date.getDay() + 1;
        // if (date < 10) {
        //   date = '0' + date;
        // }
        // let hour = date.getHours();
        // if (hour < 10) {
        //   hour = '0' + hour;
        // }
        // let mins = date.getMinutes();
        // if (mins < 10) {
        //   mins = '0' + mins
        // }
        // this.form.beginTime = year + '-' + month + '-' + day + " " + hour + ":" + mins + ":" + "00";
        this.form.beginTime = e.value[0] + " " + e.value[1]
         let date = e.value[0].substring(0, 10) + " " + this.startTime
        this.form.leaveStartTime = new Date(date).getTime();

        console.log("1111",new Date(date).getTime())
        console.log(e.value[0].substring(0, 10))
      },
      confirm(e) {
        console.log(e)
        if(this.tabIndex==0){

          this.form.type = e.value[0];
          this.form.reasonId = this.leaveReason[e.indexs[0]].id;
          console.log(this.form.reasonId)
        }else{
          this.query.reasonName = e.value[0];
          this.query.reasonId = this.leaveReason[e.indexs[0]].id;
        }
          this.typeColumnsShow = false;

      },
      confirm2(e){
        console.log("e",e)
        this.query.approvalStatusName = e.value[0];
          this.query.approvalStatus = this.attendanceStatus[e.indexs[0]].value;

          this.statusColumnsShow = false;
      },
      submit() {
        console.log(this.form)

        this.form.leaveDays = Number(this.form.leaveDays)
        // delete this.form.beginTime;
        // delete this.form.endTime;
        // delete this.form.type;
        this.form.userId = this.userId;

        if(this.userType == 3){
          this.form.userType = 2;//教师
          teacherLeaveApply(this.form).then(res=>{
            if(res.code==0){
               uni.$u.toast('申请成功')
               this.form = {};
               setTimeout(()=>{
                uni.navigateBack();
               },2000)

            }
          })
        } else if(this.userType == 4){

       this.form.userType = 1;//学生
        leaveApply(this.form).then(res => {
          if(res.code==0){
             uni.$u.toast('申请成功')
             this.form = {};
             setTimeout(()=>{
              uni.navigateBack();
             },2000)

          }
        })
         }
        return;
        this.$refs.uForm.validate().then(res => {
          uni.$u.toast('校验通过')

        }).catch(errors => {
          uni.$u.toast('校验失败')
        })
      },
      open(e) {
        // console.log('open', e)
      },
      close(e) {
        // console.log('close', e)
      },
      change(e) {
        // console.log('change', e)
      },
      btnClick(flag) {
        this.tabIndex = flag;
        if (flag == 1) {
          this.btnType1 = 'primary';
          this.btnType2 = 'default';
          return;
        }
        this.btnType1 = 'default';
        this.btnType2 = 'primary';
      }
    }
  }
</script>

<style>
page{
  background: #F8FAFB;
}
</style>

<style lang="scss" scoped>
  .main {
    width: 100%;
    height: 100%;

    .applyInfo {
      view {
        padding: 10px 0;
      }
    }

    .clock-btn {
      position: absolute;
      bottom: 5%;
      left: 50%;
      transform: translateX(-50%);
    }

    .click-btn {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: cornflowerblue;
      padding: 10px;
      line-height: 40px;
      text-align: center;

    }

    .clock {
      display: flex;
      flex-flow: wrap;

      .clock-item {
        flex: 1 0 50%;
        padding: 10px 0;
      }
    }

    .time {
      padding: 10px;
    }
  }

  .btn-group {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 44px;
    padding: 10px 10px;
    background-color: #fff;

    .btn {
      width: 45%;

    }
  }

  /deep/ .u-reset-button::after {
    border: 1px solid #ccc;
    ;
  }

  /deep/ .u-button {
    // width: 40%;
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  uni-button {
    margin: 0
  }

  ::v-deep .u-toolbar__wrapper__confirm {
    color: #3c9cff;
    font-size: 15px;
    padding: 0 15px;
    color: #C4AD8C !important;
    border: 1px solid #C4AD8C;
    border-radius: 16px;
    margin-right: 20rpx;
  }

  // ::v-deep .u-toolbar__wrapper__cancel{
  //   span{
  //     background-color: #f5f5f5;
  //     border-radius: 50%;
  //     padding:2px 5px;
  //     width: 10px;
  //     height: 10px;
  //     line-height: 10px;
  //   }
  // }
  ::v-deep .u-picker__view__column__item {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    text-align: center;
    display: block;
    /* color: #303133; */
    color: #C4AD8C;
  }
  .empty_warp{
    display: flex;
    flex-direction: column;
    align-items: center;
    .empty{
      height: 200rpx;
      width: 200rpx;
    }
    .empty_text{
      margin-top: 20rpx;
      font-size: 32rpx;
      color: #999999;
    }
  }
</style>
